package com.hcb.tonguetiphealth.widget.homepage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.ChatGridViewAdapter;
import com.hcb.tonguetiphealth.adapter.ChatListAdapter;
import com.hcb.tonguetiphealth.adapter.ChatMemberListAdapter;
import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader.ImageCallBack;
import com.hcb.tonguetiphealth.manager.ChatManager;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.MemberManager;
import com.hcb.tonguetiphealth.manager.SmileyParser;
import com.hcb.tonguetiphealth.model.Chat;
import com.hcb.tonguetiphealth.model.FileInfo;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.AbstractActivity;
import com.hcb.tonguetiphealth.view.ChatHistoryActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HomepageChatWidget2 extends GeneralWidget implements OnClickListener {
	private static final String TAG = "HomepageChatWidget";
	private String url_sendMsg = Global.URL + Global.servlet_sendMsg;
	private String url_receiveMsg = Global.URL + Global.servlet_receiveMsg;
	private String url_getMemberList = Global.URL + Global.servlet_getMemberList;
	private String url_receiveLiuyan = Global.URL + Global.servlet_receiveLiuyan;
	private String url_sendPicture = Global.URL + Global.servlet_sendPicture;
	
	private StringBuilder tagName, chatId, time;
	
	private Activity ctx;
	private Handler mHandler;
	private Button bt_addicon, bt_addpicture, bt_send;
	private LinearLayout ll_chatHistory;
	private EditText et_content;
	private TextView chatInfo, tv_name;
	private ImageView iv_img;
	private ListView listView, memberListView;
	private ChatListAdapter adapter;
	private User currentUser;
	private ChatMemberListAdapter chatMemberListAdapter;
	private List<User> memberListGlobal;
	private List<User> memberList;
	private MemberManager memberManager;
	private ChatManager chatManager;
	//private boolean processing;
	private PopupWindow myPopupWindow;
	private PopupWindow picturePopupWindow;
	private FileInfo fileInfo;
	
	public HomepageChatWidget2(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.homepage_personal_chat2, this); 
		//Global.homepageChatWidget = this;
  	    
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在请求聊天...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					break;
				case MessageWhat.PICTURE:
					System.out.println("-----------图片地址 " + (String)msg.obj);
					File file = new File((String)msg.obj);
					if(file.canRead()) {
						fileInfo = new FileInfo();
						fileInfo.setName("spic");
						fileInfo.setUrl((String)msg.obj);
						if(currentUser == null) {
							showMessage(ctx, "请选择聊天好友");
						} else {
							Chat chat = new Chat();
							chat.setUserId(Global.user.getUserId());
							chat.setMsg((String)msg.obj);
							chat.setPotraitURL(Global.user.getImgUrl());
							chat.setUserName(Global.user.getUserName());
							chat.setTime(System.currentTimeMillis()/1000);
							chat.setTagUserId(currentUser.getUserId());
							adapter.addMessage(chat);
							currentUser.addChat(chat);

							sendPicture();
						}
					} else {
						showMessage(ctx, "该图片不可发送");
					}
					break;
				case MessageWhat.CHAT_RECEIVED:
					chatMemberListAdapter.notifyDataSetChanged();
					if(currentUser != null && currentUser.isHasNewMsg()) {
						initCurrentUser();
					}
					break;
				case MessageWhat.CHAT_RECEIVED_MEMBER_SUCESS:
					if(memberList.size() > 0) {
						memberManager.saveMember(memberList);
						addAllMember(memberList);
					}
					chatMemberListAdapter.notifyDataSetChanged();
					if(currentUser != null) {
						for(User member : memberListGlobal) {
							if(member.getUserName().equals(currentUser.getUserName())) {
								currentUser = member;
								initCurrentUser();
								break;
							}
						}
					}
					break;
				case MessageWhat.CHAT_RECEIVED_MEMBER_FAILD:

					break;
				case MessageWhat.CHAT_SEND_SUCESS:
					chatInfo.setVisibility(TextView.GONE);
					break;
				case MessageWhat.CHAT_SEND_FAILD:
					chatInfo.setText("[系统提示]消息发送失败！！！");
					chatInfo.setVisibility(TextView.VISIBLE);
					break;
				case MessageWhat.CHAT_LIUYAN_RECEIVED:
					chatMemberListAdapter.notifyDataSetChanged();
					if(currentUser != null && currentUser.isHasNewMsg()) {
						initCurrentUser();
					}
					break;
				}
			}
		};
		iv_img = (ImageView)findViewById(R.id.homepage_personal_chat_current_member_img);
		tv_name = (TextView)findViewById(R.id.homepage_personal_chat_current_member_name);
		chatInfo = (TextView)findViewById(R.id.homepage_personal_chat_info_textview);
		listView = (ListView)findViewById(R.id.homepage_personal_chat_listview);
		memberListView = (ListView)findViewById(R.id.homepage_personal_chat_member_listview);
		bt_addicon = (Button)findViewById(R.id.homepage_personal_chat_add_icon_button);
		bt_addpicture = (Button)findViewById(R.id.homepage_personal_chat_add_picture_button);
		bt_send = (Button)findViewById(R.id.homepage_personal_chat_send_button);
		ll_chatHistory = (LinearLayout)findViewById(R.id.homepage_personal_chat_history_linearlayout);
		et_content = (EditText)findViewById(R.id.homepage_personal_chat_content_edittext);
		bt_addicon.setOnClickListener(this);
		bt_addpicture.setOnClickListener(this);
		bt_send.setOnClickListener(this);
		ll_chatHistory.setOnClickListener(this);
		memberListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				User user = (User)arg0.getAdapter().getItem(arg2);
				if(currentUser == null || !currentUser.getUserName().equals(user.getUserName())) {
					currentUser = user;
					initCurrentUser();
				}
			}
		});
		initData();
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.homepage_personal_chat_add_icon_button:
			//关闭软键盘
			InputMethodManager imm = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0);
			myPopupWindow.showAsDropDown(bt_addicon, 0, 10);
			break;
		case R.id.homepage_personal_chat_add_picture_button:
			if(currentUser == null) {
				showMessage(ctx, "请选择聊天好友");
			} else {
				AbstractActivity.setHandler(mHandler);
				picturePopupWindow.showAsDropDown(bt_addpicture, -60, 10);
			}
			break;
		case R.id.homepage_personal_chat_send_button:
			if(et_content.getText().toString().length() != 0){
				if(currentUser == null) {
					showMessage(ctx, "请选择聊天好友");
				} else {
					sendMsg(et_content.getText().toString());
					chatInfo.setVisibility(TextView.GONE);
					Chat chat = new Chat();
					chat.setUserId(Global.user.getUserId());
					chat.setMsg(et_content.getText().toString());
					chat.setPotraitURL(Global.user.getImgUrl());
					chat.setUserName(Global.user.getUserName());
					chat.setTime(System.currentTimeMillis()/1000);
					chat.setTagUserId(currentUser.getUserId());
					adapter.addMessage(chat);
					currentUser.addChat(chat);
					et_content.setText(null);
				}
			} else {
				showMessage(ctx, "不能发送空消息");
			}
			break;
		case R.id.homepage_personal_chat_history_linearlayout:
			if(currentUser == null) {
				showMessage(ctx, "请选择聊天好友");
			} else {
				Intent intent = new Intent(ctx, ChatHistoryActivity.class);
				intent.putExtra("user", currentUser);
				ctx.startActivity(intent);
			}
			break;
		default:
			break;
		}
	}
	private void addAllMember(List<User> members) {
		boolean find = false;
		for(User m : members) {
			find = false;
			for(User u : memberListGlobal) {
				if(m.getUserName().equals(u.getUserName())) {
					updateUserInfo(u, m);
					find = true;
					break;
				}
			}
			if(!find) {
				memberListGlobal.add(m);
			}
		}
	}
	private void updateUserInfo(User user, User newUser) {
		user.setRealName(newUser.getRealName());
		user.setImgUrl(newUser.getImgUrl());
	}
	private void initCurrentUser() {
		Global.currentChatUser = currentUser;
		if(currentUser.isHasNewMsg()) {
			currentUser.setHasNewMsg(false);
			chatMemberListAdapter.notifyDataSetChanged();
		}
		
		adapter.setMsgs(currentUser.getChatList());
		//listView.smoothScrollToPosition(adapter.getCount()-1);
		
		tv_name.setText(currentUser.getRealName());
		AsyncBitmapLoader asyncBitmapLoader = AsyncBitmapLoader.getInstance();
		String imageURL = currentUser.getImgUrl();  
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(iv_img, imageURL, new ImageCallBack() {  
              
            public void imageLoad(ImageView imageView, Bitmap bitmap) {  
                // TODO Auto-generated method stub  
            	if(bitmap == null) {
            		imageView.setImageResource(R.drawable.ic_launcher); 
            	} else {
            		imageView.setImageBitmap(bitmap);  
            	}
            }  
        });  
		if(bitmap == null) {    
			iv_img.setImageResource(R.drawable.ic_launcher);    
		} else {    
			iv_img.setImageBitmap(bitmap);    
		}
	}
	public void initCurrentUser(User member) {
		if(memberListGlobal != null) {
			boolean find = false;
			for(User mUser : memberListGlobal) {
				if(member.getUserName().equals(mUser.getUserName())) {
					currentUser = mUser;
					updateUserInfo(mUser, member);
					find = true;
					break;
				}
			}
			if(!find) {
				currentUser = member;
				memberManager.saveMember(member);
				memberListGlobal.add(member);
				chatMemberListAdapter.notifyDataSetChanged();
			} 
			initCurrentUser();
		}
	}
	private void initData() {
		tagName = new StringBuilder();
		chatId = new StringBuilder();
		time = new StringBuilder();
		adapter = new ChatListAdapter(ctx);
		listView.setAdapter(adapter);
		
		memberManager = new MemberManager(ctx);
		chatManager = new ChatManager(ctx);
		memberList = new ArrayList<User>();
		if(Global.memberList == null) {
			Global.memberList = new ArrayList<User>();
			Global.memberList = new MemberManager(ctx).getMemberList(Global.memberList);
		}
		memberListGlobal = Global.memberList;
		
		String from = ctx.getIntent().getStringExtra("from");
		if(from != null && from.equals("TongueTipHealthService")) {
			currentUser = (User)ctx.getIntent().getSerializableExtra("user");
	  	    
	  	    boolean find = false;
			for(User member : memberListGlobal) {
				if(member.getUserName().equals(currentUser.getUserName())) {
					member.setChatId(currentUser.getChatId());
					member.setTime(currentUser.getTime());
					currentUser = member;
					find = true;
					updateUserInfo(member, currentUser);
					initCurrentUser();
					break;
				}
			} 
			if(!find) {
		  	    memberManager.saveMember(currentUser);
		  	    memberListGlobal.add(currentUser);
		  	    initCurrentUser();
			}
		} else if(Global.currentChatUser != null) {
			for(User member : memberListGlobal) {
				if(member.getUserName().equals(Global.currentChatUser.getUserName())) {
					currentUser = member;
					initCurrentUser();
					break;
				}
			}
		}
		
		chatMemberListAdapter = new ChatMemberListAdapter(ctx, memberListGlobal);
		memberListView.setAdapter(chatMemberListAdapter);
		
		// 初始化表情解析器（将文本解析为表情图标显示，如[微笑] 显示微笑图标）
	    SmileyParser.init(ctx);
		setPopupWindow();
		picturePopupWindow = makePicturePopupWindow();
		
		if(!Global.isReceivingChat) {
			Global.isReceivingChat = true;
			
			getMemberList();
			receiveMsg();
		} else {
			//mHandler.sendEmptyMessage(MessageWhat.CHAT_RECEIVED_MEMBER_SUCESS);
		}
		
		String from1 = ctx.getIntent().getStringExtra("from");
		System.out.println("from1:::::::::::::"+from1);
		if ("TongueTipHealthServiceLiuYan".equals(from1)) {
			System.out.println("liuyan-----------widget2");
			String response = ctx.getIntent().getStringExtra("response");
			System.out.println("rensponse-----------111111111111----"+response);
			receiveLiuyan(response);
		}
		
		
	}
	private void getMemberList() {
		new Thread() {
			public void run() {
				memberList.clear();
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
					response = HttpUtils.Post(url_getMemberList, params);
					
					if(Global.DEBUG) {
						System.out.println("getMemberList -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					User user;
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							
						} else {
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									user = new User();
									user.setUserId(getString(jObject, "userid"));
									user.setUserName(getString(jObject, "username"));
									user.setImgUrl(getString(jObject, "headicon"));
									user.setRealName(getString(jObject, "truename"));
									
									if(!user.getUserName().equals(Global.user.getUserName())) {
										memberList.add(user);
									}
								}
							}
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.CHAT_RECEIVED_MEMBER_SUCESS);
			}
		}.start();
	}
	
	/**
	 * 发送消息
	 * @param message
	 */
	private void sendMsg(final String message) {
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("tagName", currentUser.getUserName()));
					params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
					params.add(new BasicNameValuePair("chatId", currentUser.getChatId()));
					params.add(new BasicNameValuePair("message", message));
					response = HttpUtils.Post(url_sendMsg, params);
					
					if(Global.DEBUG) {
						System.out.println("sendMsg -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject2(response);
					if(isGotJSONObject) {
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						JSONObject jo = jManager.getJsonObject();
						currentUser.setChatId(getString(jo, "chatid"));
						if(currentUser.getTime() == 0) {
							currentUser.setTime(StringUtils.parseLong(getString(jo, "time")));
						}
						
						System.out.println("------ 得到msg: " + count + ":" + msg 
								+ ":" + currentUser.getChatId());
						mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_SUCESS);
					} else {
						mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_FAILD);
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_FAILD);
				}
			}
		}.start();
	}
	private void sendPicture(){
		//mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("tagName", currentUser.getUserName()));
				params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
				params.add(new BasicNameValuePair("chatId", currentUser.getChatId()));
				/*List<FileInfo>fileList = new ArrayList<FileInfo>();
				fileList.add(fileInfo);*/
				//String response = HttpUtils.Post(Global.getServletheadportrait(), params, fileList);
				System.out.println("fileinfo"+fileInfo.getUrl());
				String response = HttpUtils.PostFile(url_sendPicture, params, fileInfo);
				if (Global.DEBUG) {
					System.out.println("上传图片返回信息：------------------------------\n" + response);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject2(response);
					if(isGotJSONObject) {
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						JSONObject jo = jManager.getJsonObject();
						currentUser.setChatId(getString(jo, "chatid"));
						if(currentUser.getTime() == 0) {
							currentUser.setTime(StringUtils.parseLong(getString(jo, "time")));
						}
						System.out.println("------ 上传图片msg: " + count + ":" + msg + ":" + currentUser.getChatId());
						mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_SUCESS);
					} else {
						mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_FAILD);
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.CHAT_SEND_FAILD);
				}
				//mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	private void initPostParams() {
		tagName.setLength(0);
		chatId.setLength(0);
		time.setLength(0);
		for(User member : memberListGlobal) {
			if(!member.getChatId().equals("-1")) {
				tagName.append(member.getUserName()).append(",");
				chatId.append(member.getChatId()).append(",");
				/*if(member.getTime()==0) {
					member.setTime(System.currentTimeMillis()/1000);
				}*/
				time.append(member.getTime()).append(",");
			}
		}
	}
	/**
	 * 接收消息
	 */
	private void receiveMsg() {
		new Thread() {
			public void run() {
				while(Global.running && Global.isReceivingChat) {
					String response = null;
					initPostParams();
					if(currentUser != null && tagName.length() > 0) {
						try {
							List <NameValuePair> params = new ArrayList <NameValuePair>();
							params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
							params.add(new BasicNameValuePair("tagName", tagName.toString())); 
							params.add(new BasicNameValuePair("chatId", chatId.toString()));
							params.add(new BasicNameValuePair("time", time.toString()));
							response = HttpUtils.Post1(url_receiveMsg, params);
							
							if(Global.DEBUG) {
								System.out.println("receiveMsg -----------------------------\n" 
										+ Global.user.getUserName()
										+ " : " + tagName.toString()
										+ " : " + chatId.toString()
										+ " : " + time.toString());
								System.out.println("receiveMsg -----------------------------\n" + response);
							}
						} catch(Exception e) {
							Log.e(TAG, "Exception", e); 
						}
						if(!StringUtils.isEmpty(response)) {
							JSONManager jManager = new JSONManager();
							boolean isGotJSONObject = jManager.isGotJSONObject(response);
							if(isGotJSONObject) {
								JSONArray jsonList = jManager.getJsonList();
								if(jsonList != null && jsonList.length() > 0) {
									JSONObject json, jsonChat;
									JSONArray jsonArray;
									User tempUser = null;
									Chat chat = null;
									boolean find = false;
									for(int i=0; i<jsonList.length(); i++) {
										json = getJSONObject(jsonList, i);
										jsonArray = getJSONArray(json, "msg");
										find = false;
										for(User member : memberListGlobal) {
											if(member.getUserName().equals(getString(json, "username"))) {
												tempUser = member;
												find = true;
											}
										}
										if(jsonArray != null && jsonArray.length()>0 && find) {
											tempUser.setHasNewMsg(true);
											for(int j=0; j<jsonArray.length(); j++) {
												jsonChat = getJSONObject(jsonArray, j);
												chat = new Chat();
												chat.setMsg(getString(jsonChat, "word"));
												chat.setTime(StringUtils.parseLong(getString(jsonChat, "time")));
												chat.setUserName(getString(json, "username"));
												chat.setPotraitURL(getString(json, "img"));
												chat.setUserId(getString(json, "userid"));
												chat.setRealName(getString(json, "truename"));
												chat.setTagUserId(chat.getUserId());
												
												tempUser.setTime(chat.getTime());
												tempUser.addChat(chat);
												chatManager.saveChat(chat);
											}
											System.out.println("++++++++ 接收到新消息:-------------------\n "
											         + tempUser.getRealName()+" : "+chat.getMsg());
											mHandler.sendEmptyMessage(MessageWhat.CHAT_RECEIVED);
										}
									}
								}
								int count = jManager.getResult();
								String msg = jManager.getMsg();
								System.out.println("------ 得到msg: " + count + ":" + msg);
							}
						}
					}
					
					for(int i=1; i<=16; i++) {
						if(Global.running && Global.isReceivingChat) {
							try {
								Thread.sleep(500);
							} catch (InterruptedException e1) {
								e1.printStackTrace();
							}
						} else {
							break;
						}
					}
				}
			}
		}.start();
	}
	
	/**
	 * 接收留言
	 */
	private void receiveLiuyan(final String response) {
		new Thread() {
			public void run() {
				/*String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
					response = HttpUtils.Post1(url_receiveLiuyan, params);
					
					if(Global.DEBUG) {
						System.out.println("receiveLiuyan -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e); 
				}*/
				System.out.println("rensponse---------------"+response);
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jsonList = jManager.getJsonList();
						if(jsonList != null && jsonList.length() > 0) {
							JSONObject json, jsonChat;
							JSONArray jsonArray;
							User tempUser = null;
							Chat chat;
							boolean find = false;
							for(int i=0; i<jsonList.length(); i++) {
								json = getJSONObject(jsonList, i);
								jsonArray = getJSONArray(json, "msg");
								find = false;
								for(User member : memberListGlobal) {
									if(member.getUserId().equals(getString(json, "userid"))) {
										member.setRealName(getString(json, "truename"));
										member.setImgUrl(getString(json, "img"));
										tempUser = member;
										find = true;
									}
								}
								if(!find) {
									tempUser = new User();
									tempUser.setUserName(getString(json, "username"));
									tempUser.setImgUrl(getString(json, "img"));
									tempUser.setUserId(getString(json, "userid"));
									tempUser.setRealName(getString(json, "truename"));
									memberManager.saveMember(tempUser);
									memberListGlobal.add(tempUser);
								}
								tempUser.setHasNewMsg(true);
								for(int j=0; j<jsonArray.length(); j++) {
									jsonChat = getJSONObject(jsonArray, j);
									chat = new Chat();
									chat.setMsg(getString(jsonChat, "word"));
									chat.setTime(StringUtils.parseLong(getString(jsonChat, "time")));
									chat.setUserName(getString(json, "username"));
									chat.setPotraitURL(getString(json, "img"));
									chat.setUserId(getString(json, "userid"));
									chat.setRealName(getString(json, "truename"));
									chat.setTagUserId(chat.getUserId());
									
									tempUser.addChat(chat);
									chatManager.saveChat(chat);
								}
							}
							mHandler.sendEmptyMessage(MessageWhat.CHAT_LIUYAN_RECEIVED);
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
			}
		}.start();
	}
	
	private void startCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		 if(Global.chatActivity[0] != null) {
			 Global.chatActivity[0].startActivityForResult(intent, 1);
		 } else  if(Global.chatActivity[1] != null) {
			 Global.chatActivity[1].startActivityForResult(intent, 1);
		 }
		//ctx.startActivityForResult(intent, 1);
	}
    private void startLocalFiles(){
		Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        /* 取得相片后返回本画面 */
        if(Global.chatActivity[0] != null) {
			 Global.chatActivity[0].startActivityForResult(intent, 2);
		 } else  if(Global.chatActivity[1] != null) {
			 Global.chatActivity[1].startActivityForResult(intent, 2);
		 }
    	//ctx.startActivityForResult(intent, 2);
	}
  //创建一个包含自定义view的PopupWindow
	private PopupWindow makePicturePopupWindow() {
	    PopupWindow window;
	    window = new PopupWindow(ctx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.drinks_book_dialog_list, null); 
        listView = (ListView)view.findViewById(R.id.drinks_book_dialog_listview);
        List<String> selectList = new ArrayList<String>();
	  	selectList.add("拍照");
		selectList.add("从本地相册");
        SelectionListAdapter adapter = new SelectionListAdapter(ctx, selectList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				switch (arg2) {
				case 0:
					startCamera();
					break;
				case 1:
					startLocalFiles();
					break;
				default:
					break;
				}
				picturePopupWindow.dismiss();
			}
		});
	    view.setBackgroundColor(ctx.getResources().getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    window.setWidth(160);
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    window.setHeight(100);
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	/**展示window*/
	private void setPopupWindow(){
		GridView gridView = new GridView(ctx);
		ChatGridViewAdapter adapter = new ChatGridViewAdapter(ctx);
		gridView.setAdapter(adapter);
		gridView.setNumColumns(6);
		gridView.setBackgroundColor(Color.rgb(214, 211, 214));
		gridView.setHorizontalSpacing(1);
		gridView.setVerticalSpacing(1);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		gridView.setGravity(Gravity.CENTER);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				 myPopupWindow.dismiss();
				CharSequence convertContent = SmileyParser.getInstance()
				.addSmileySpans(SmileyParser.mSmileyTexts[arg2]);
				//et_content.setText(convertContent);
				et_content.append(convertContent);
				et_content.setSelection(et_content.getText().length());
			}
		});
		//myPopupWindow= new PopupWindow(gridView, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT, true);
	    myPopupWindow = new PopupWindow(gridView,LayoutParams.FILL_PARENT,200, true);//LayoutParams.WRAP_CONTENT
		myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		myPopupWindow.setAnimationStyle(R.style.PopupAnimation_buttom);
	 // myPopupWindow.showAtLocation(findViewById(R.id.rlayout), Gravity.LEFT| Gravity.LEFT, 0, 0);
		myPopupWindow.update();//更新当前状态，比如展开或者关闭等等
			 
	}
	
	@Override
	public void notifyAdapter() {
		if(currentUser != null) {
			adapter.setMsgs(currentUser.getChatList());
		}
	}
	/*public boolean isProcessing() {
		return processing;
	}
	public void setProcessing(boolean processing) {
		this.processing = processing;
	}*/
	public User getCurrentUser() {
		return currentUser;
	}
	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}
}
